import init, { Game } from '../pkg/grass_cutting_game.js';

let game;
let canvas;
let ctx;
let animationId;
let grassStylesCache = new Map();

async function initGame() {
    await init();
    game = Game.new();
    game.init_level(1);
    
    canvas = document.getElementById('game-canvas');
    ctx = canvas.getContext('2d');
    
    // 创建自定义光标元素
    const cursor = document.createElement('img');
    cursor.src = './assets/mower-cursor.png';
    cursor.style.cssText = `
        position: fixed;
        pointer-events: none;
        width: 32px;
        height: 32px;
        transform: translate(-16px, -16px);
        z-index: 9999;
    `;
    document.body.appendChild(cursor);
    
    // 隐藏默认光标
    canvas.style.cursor = 'none';
    
    // 合并原有的mousemove事件和光标更新
    canvas.addEventListener('mousemove', (e) => {
        // 更新自定义光标位置
        cursor.style.left = e.clientX + 'px';
        cursor.style.top = e.clientY + 'px';
        
        // 原有的游戏逻辑
        const rect = canvas.getBoundingClientRect();
        game.move_player(
            e.clientX - rect.left,
            e.clientY - rect.top
        );
    });
    
    // 鼠标离开canvas时隐藏自定义光标
    canvas.addEventListener('mouseout', () => {
        cursor.style.display = 'none';
    });
    
    // 鼠标进入canvas时显示自定义光标
    canvas.addEventListener('mouseover', () => {
        cursor.style.display = 'block';
    });
    
    // 设置画布大小
    function resizeCanvas() {
        canvas.width = window.innerWidth - 40;
        canvas.height = window.innerHeight - 100;
    }
    resizeCanvas();
    window.addEventListener('resize', resizeCanvas);
    
    // 暂停按钮事件处理
    document.getElementById('pause-btn').addEventListener('click', () => {
        game.toggle_pause();
    });
    
    // 重新开始按钮事件处理
    document.getElementById('restart-btn').addEventListener('click', () => {
        grassStylesCache.clear();
        game = Game.new();
        game.init_level(1);
    });
    
    // 添加关卡选择功能
    const levelButtons = document.querySelectorAll('.level-btn');
    levelButtons.forEach(button => {
        button.addEventListener('click', () => {
            grassStylesCache.clear();
            const level = parseInt(button.dataset.level);
            game = Game.new();
            game.init_level(level);
            
            levelButtons.forEach(btn => btn.classList.remove('active'));
            button.classList.add('active');
        });
    });
    
    // 设置第一关按钮为激活状态
    document.querySelector('.level-btn[data-level="1"]').classList.add('active');
    
    function gameLoop() {
        if (!game.is_paused) {
            drawGame();
        }
        requestAnimationFrame(gameLoop);
    }
    gameLoop();
}

function drawGame() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    const grassPositions = game.get_grass_positions();
    
    for (let i = 0; i < grassPositions.length; i += 2) {
        const x = grassPositions[i];
        const y = grassPositions[i + 1];
        
        // 为每个位置创建唯一的key
        const posKey = `${x},${y}`;
        
        // 如果这个位置还没有缓存的样式，创建并缓存它
        if (!grassStylesCache.has(posKey)) {
            const grassStyles = {
                count: Math.floor(Math.random() * 3) + 1,
                grasses: []
            };
            
            // 预先生成每棵草的样式
            for (let j = 0; j < grassStyles.count; j++) {
                const grass = {
                    offsetX: Math.random() * 10 - 5,
                    offsetY: Math.random() * 6 - 3,
                    stemHeight: 8 + Math.random() * 4,
                    stemAngle: (Math.random() * 0.6 - 0.3) * Math.PI,
                    leafCount: Math.floor(Math.random() * 2) + 2,
                    leaves: []
                };
                
                // 预先生成每片叶子的样式
                for (let k = 0; k < grass.leafCount; k++) {
                    grass.leaves.push({
                        color: ['#3a7729', '#4a8532', '#2d5a27'][Math.floor(Math.random() * 3)],
                        position: 0.3 + (k * 0.3) + Math.random() * 0.2,
                        angle: (k % 2 ? 0.8 : -0.8) + (Math.random() * 0.4 - 0.2),
                        length: 4 + Math.random() * 3
                    });
                }
                
                grassStyles.grasses.push(grass);
            }
            
            grassStylesCache.set(posKey, grassStyles);
        }
        
        // 使用缓存的样式绘制草
        const styles = grassStylesCache.get(posKey);
        styles.grasses.forEach(grass => {
            const stemEndX = x + grass.offsetX + Math.sin(grass.stemAngle) * grass.stemHeight;
            const stemEndY = y + grass.offsetY - Math.cos(grass.stemAngle) * grass.stemHeight;
            
            // 绘制茎
            ctx.beginPath();
            ctx.strokeStyle = '#2d5a27';
            ctx.lineWidth = 1.5;
            ctx.moveTo(x + grass.offsetX, y + grass.offsetY);
            ctx.lineTo(stemEndX, stemEndY);
            ctx.stroke();
            
            // 绘制叶子
            grass.leaves.forEach(leaf => {
                ctx.fillStyle = leaf.color;
                
                const leafX = x + grass.offsetX + Math.sin(grass.stemAngle) * (grass.stemHeight * leaf.position);
                const leafY = y + grass.offsetY - Math.cos(grass.stemAngle) * (grass.stemHeight * leaf.position);
                const leafAngle = grass.stemAngle + leaf.angle;
                
                ctx.beginPath();
                ctx.moveTo(leafX, leafY);
                
                const controlX = leafX + Math.cos(leafAngle) * leaf.length * 2;
                const controlY = leafY + Math.sin(leafAngle) * leaf.length * 2;
                const endX = leafX + Math.cos(leafAngle) * leaf.length;
                const endY = leafY + Math.sin(leafAngle) * leaf.length;
                
                ctx.quadraticCurveTo(controlX, controlY, endX, endY);
                ctx.quadraticCurveTo(
                    leafX + Math.cos(leafAngle + 0.2) * leaf.length,
                    leafY + Math.sin(leafAngle + 0.2) * leaf.length,
                    leafX,
                    leafY
                );
                ctx.fill();
            });
        });
    }
    
    // 更新界面上的分数和关卡显示
    document.getElementById('score').textContent = game.get_score();
    document.getElementById('level').textContent = game.get_level();
    
    // 检查关卡是否完成
    if (game.is_level_complete()) {
        const nextLevel = game.get_level() + 1;
        if (nextLevel <= 3) {
            game.init_level(nextLevel);
        } else {
            alert('恭喜通关！');
            game = Game.new();
            game.init_level(1);
        }
    }
}

// 创建游戏开始屏幕
function createStartScreen() {
    const startScreen = document.createElement('div');
    startScreen.id = 'start-screen';
    startScreen.innerHTML = `
        <h1>欢迎来到游戏</h1>
        <button id="start-button">开始游戏</button>
    `;
    document.body.appendChild(startScreen);

    // 添加按钮点击事件
    document.getElementById('start-button').addEventListener('click', () => {
        startScreen.style.display = 'none'; // 隐藏开始屏幕
        // 这里可以调用游戏初始化逻辑
        init(); // 确保不改变现有逻辑
    });
}

// 在页面加载时创建开始屏幕
window.onload = () => {
    createStartScreen();
    // ... 其他初始化代码 ...
};

initGame().catch(console.error);